'''
Created on Sep 4, 2011

@author: david
'''
from app.G6.actions import G6Action

class Edit(G6Action):
    """
    Default Action 
    spawns index.gen
    """
    def execute(self):
        import logging
        from app.G6.agents import AccountAgent
        import simplejson as json
        
        req = self.request
        
        acct = None
        rslts = "200::OK"
        nxtPage = "/G6/account.gen"
        
        agent = AccountAgent()
        try:
            logging.debug(self.sess_check())
            # new account request?
            if self.auth_check():
                # nope, get existing account
                acct = req.session['acct']
                req.setAttribute("mode","update")
                
                # break up the name too
                nm = acct.name.split("::")
                req.setAttribute("fname",nm[0])
                req.setAttribute("lname",nm[1])

            else:
                # send out clean slate
                logging.debug("~~ New Account Request coming through...")
                acct = agent.fetch('','',createEmpty=True)
                req.setAttribute("mode","new")
                req.setAttribute("fname",'')
                req.setAttribute("lname",'')
                
            # pass to template
            req.setAttribute("acct",acct)
            req.setAttribute("acctJSON",json.dumps(acct.toJSON()))
        except Exception, ex:
            "make sense"
            logging.exception("!! Edit Account Action Error: %s" % str(ex))
            rslts = "500::Action Error: %s" % str(ex)
            req.setAttribute("mode", "error")
            nxtPage = "/site_error.gen"
            
        req.setAttribute("results",rslts)
        req.setResponsePage(nxtPage)        
        
        return req.getResponse()
